package com.tuling.netty.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

public class NettyByteBuf {
    public static void main(String[] args) {
        //创建byteBuf对象，该对象内部包含了一个字节数组
        //通过readerIndex和writerIndex和capacity将buffer分成三个区域
        //已经读取的区域:[0,readerIndex]
        //可读取的区域:[readerIndex,writerIndex)
        //可写的区域:[writerIndex,capacity)
        ByteBuf byteBuf = Unpooled.buffer(10);
        System.out.println("byteBuf = " + byteBuf);

        for (int i = 0; i < 8; i++) {
            byteBuf.writeByte(i);
        }
        System.out.println("byteBuf = " + byteBuf);

        for (int i = 0; i < 5; i++) {
            System.out.println("byteBuf = " + byteBuf.getByte(i));
        }

        System.out.println("byteBuf = " + byteBuf);

        for (int i = 0; i < 5; i++) {
            System.out.println("byteBuf = " + byteBuf.readByte());
        }

        System.out.println("byteBuf = " + byteBuf);

        //用Unpooled工具创建ByteBuf
        ByteBuf buf = Unpooled.copiedBuffer("hello,ZhuGe", CharsetUtil.UTF_8);
        //使用相关方法
        if (buf.hasArray()) {
            byte[] content = buf.array();
            // 将content转成字符串
            System.out.println(new String(content,CharsetUtil.UTF_8));
            System.out.println("buf = " + buf);
            System.out.println(buf.getByte(0));// 获取数组0这个位置的字符h的ascii码，h=104

            int len = buf.readableBytes();//可读的字节数
            System.out.println("len = " + len);

            // 使用for取出各个字节
            for (int i = 0; i < len; i++) {
                System.out.println((char)buf.getByte(i));
            }
            // 范围读取
            System.out.println(buf.getCharSequence(0, 6, CharsetUtil.UTF_8));
        }


    }
}
